<template>
  <el-card shadow="always" :body-style="{ padding: '20px' }">
    <div slot="header">
      <span>
        <!-- card title -->
        基本资料
      </span>
    </div>
    <!-- card body -->
    <!-- 内容区域 -->
    <!-- 表单区域 -->
    <el-form
      :model="userInfo"
      ref="form"
      :rules="rules"
      label-width="80px"
      style="padding-left: 20px"
    >
      <el-form-item label="登录名称">
        <el-input v-model="userInfo.username" disabled class="input"></el-input>
      </el-form-item>
      <el-form-item label="用户昵称" prop="nickname">
        <el-input v-model="userInfo.nickname" class="input"></el-input>
      </el-form-item>
      <el-form-item label="用户邮箱" prop="email">
        <el-input v-model="userInfo.email" class="input"></el-input>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="onSubmit">提交修改</el-button>
        <el-button @click="reset">重置</el-button>
      </el-form-item>
    </el-form>
  </el-card>
</template>

<script>
import { updateUserInfoApi } from '@/api/user'
export default {
  name: 'UserInfo',
  data () {
    return {
      // vuex存贮的数据是请求结束（异步）后才赋值的，所以刚开始拿到的数值是空的，所以需要监听vuex中的数据变化
      userInfo: this.$store.state.user.userInfo,
      rules: {
        nickname: [
          { required: true, message: '请输入用户昵称', trigger: 'blur' },
          { pattern: /^\S{2,10}$/, message: '昵称必须是1-10位的非空字符串', trigger: 'blur' }
        ],
        email: [
          { required: true, message: '请输入邮箱地址', trigger: 'blur' },
          { type: 'email', message: '请输入正确的邮箱地址', trigger: ['blur', 'change'] }
        ]
      }
    }
  },
  methods: {
    onSubmit () {
      this.$refs.form.validate(async (isOk) => {
        if (isOk) {
          await updateUserInfoApi(this.userInfo)
          this.$store.dispatch('user/getUserAction')
          this.$message.success('修改成功')
        }
      })
    },
    reset () {
      this.$refs.form.resetFields()
    }
  },
  watch: {
    // 数据变化后，重新赋值
    '$store.state.user.userInfo': {
      // 组件重新挂载后，立即执行一次
      immediate: true,
      handler (newValue) {
        // newValue和vuex中变量是引用关系=>需要浅拷贝
        // this.userInfo = newValue
        this.userInfo = { ...newValue }
      }
    }
  }
}
</script>

<style lang="less" scoped>
.input {
  width: 368px;
}
</style>
